package com.bbs.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bbs.exception.BusinessException;
import com.bbs.mapper.UserMapper;
import com.bbs.pojo.User;
import com.bbs.pojo.dto.UserDto;
import com.bbs.service.UserService;
import com.bbs.utils.PasswordChecker;
import com.mysql.cj.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Override
    public UserDto getUserDtoById(String id) {
        //排除头像字段
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.select(User.class, info-> !info.getColumn().equals("avatar"));
        queryWrapper.eq("user_id", id);

        User user = getOne(queryWrapper);
        if(user != null){
            return new UserDto(getById(id));
        }else{
            return null;
        }
    }

    @Override
    public List<UserDto> getUserDtos(UserDto userDto) {
        User user = new User();
        user.setUserId(userDto.getUserId());
        user.setUsername(userDto.getUsername());
        user.setSex(userDto.getSex());

        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.setEntity(user);

        //排除头像字段
        queryWrapper.select(User.class, info-> !info.getColumn().equals("avatar"));

        List<User> users = list(queryWrapper);
        return users.stream().map(UserDto::new).collect(Collectors.toList());
    }

    //注册用户用的服务
    @Override
    public boolean register(User user) {

        //检查传入的用户对应的用户id是否已经存在
        if (getById(user.getUserId()) != null) {
            throw new BusinessException("该用户id已经存在，请检查");
        }

        //检查用户名是否为空
        String username = user.getUsername();
        if (username == null) {
            throw new BusinessException("用户名为空，请重试");
        }
        //检查用户名长度是否符合要求
        int minUsernameLength = 6;
        int maxUsernameLength = 32;
        if (username.length() < minUsernameLength || username.length() > maxUsernameLength) {
            String userNameLengthErrorMessage = "用户名的长度不符合要求，用户名的长度必须不少于" + minUsernameLength + "并且必须少于" + maxUsernameLength;
            throw new BusinessException(userNameLengthErrorMessage);
        }

        final String NORMAL_USER = "ROLE_NORMAL_USER";

        String password = user.getPassword().trim();
        user.setPassword(password);
        //检查密码是否为空
        if (StringUtils.isNullOrEmpty(password)) {
            throw new BusinessException("密码为空");
        }

        //检查用户的密码是否合法
        PasswordChecker.PasswordCheckResult passwordCheckResult = PasswordChecker.checkPassword(password);
        if (passwordCheckResult != PasswordChecker.PasswordCheckResult.SUCCESS) {
            throw new BusinessException(passwordCheckResult.getMessage());
        }

        //检查用户的密码长度是否符合要求
        int minPasswordLength = 6;
        int maxPasswordLength = 32;
        if (password.length() < minPasswordLength || password.length() > maxPasswordLength) {
            String userPasswordLengthErrorMessage = "密码的长度不符合要求，密码的长度不得短于" + minPasswordLength + "且不得长于" + maxPasswordLength;
            throw new BusinessException(userPasswordLengthErrorMessage);
        }

        //覆盖字段
        user.setRole(NORMAL_USER);
        user.setExperience(0);
        return save(user);
    }

    @Override
    public boolean updateExperience(String id, Integer deltaExperience) {
        User user = getById(id);
        if (user == null) {
            throw new BusinessException("用户不存在");
        }
        user.setExperience(user.getExperience() + deltaExperience);
        return updateById(user);
    }


    //根据用户id和传入的图片将用户的头像传入数据库中
    @Override
    public boolean setAvatarById(String id, byte[] avatar) {
        LambdaUpdateWrapper<User> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(User::getUserId, id);
        wrapper.set(User::getAvatar, avatar);
        return update(wrapper);
    }

    //根据用户id删除头像
    @Override
    public boolean RemoveAvatarById(String id) {
        LambdaUpdateWrapper<User> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(User::getUserId, id);
        wrapper.set(User::getAvatar, null);
        return update(wrapper);
    }

    @Override
    public User getUser(String username) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        User user = new User();
        user.setUsername(username);
        queryWrapper.setEntity(user);

        //排除头像字段
        queryWrapper.select(User.class, info-> !info.getColumn().equals("avatar"));

        return getOne(queryWrapper, true);
    }

    @Override
    public boolean addExperience(String id, Integer experience) {
        User user = new User();
        user.setUserId(id);
        user = getOne(new QueryWrapper<>(user));
        user.setExperience(user.getExperience() + experience);
        return updateById(user);
    }
}
